<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Channels;
use App\Models\Games;
use App\Models\SpinWheelUser;
use App\Services\GameChannelService;
use App\Services\SpinWheelService;
use App\Services\WanSdk\WanSdkService;
use Illuminate\Http\Request;

class SpinWheelController extends Controller
{
    public function index(Request $request, $game_id)
    {
        $channel         = Channels::CHANNEL_H5;
        $game_channel_id = $request->input('game_channel_id') ?? 0;
        $game_channel_id = GameChannelService::getInstance()->checkAndGetId($game_id, $channel, $game_channel_id);
        $params = [
            'game_channel_id' => $game_channel_id,
        ];
        $url = WanSdkService::getInstance()->getWechatOauthUrl($game_id, $game_channel_id, $params, 'spin_wheel/oauth');
        return redirect()->away($url);
    }

    public function oauthCb(Request $request)
    {
        $game_id         = $request->input('game_id') ?? 1005;
        $channel         = Channels::CHANNEL_H5;
        $game_channel_id = $request->input('game_channel_id') ?? 0;
        $code            = $request->input('code') ?? '';

        $openid = '';
        if (!empty($code)) {
            $game_channel_id = GameChannelService::getInstance()->checkAndGetId($game_id, $channel, $game_channel_id);
            $info = WanSdkService::getInstance()->getWechatOffiaccountInfo($game_id, $game_channel_id, $code);
            if (empty($info)) {
                return yqerr(6026);
            }
            $openid = $info['openid'];
        }

        $user = SpinWheelService::getInstance()->createOrUpdateUser($game_id, $openid);

        return view('spin_wheel.index', [
            'game_id'     => $game_id,
            'openid'      => $user['openid'],
            'lottery_num' => $user['lottery_num'],
            'rule_list'   => SpinWheelService::getInstance()->getRuleList($user),
            'prize_list'  => SpinWheelService::getInstance()->getPrizeList(),
        ]);
    }

    public function lottery(Request $request)
    {
        $res = SpinWheelService::getInstance()->lottery($request);
        if (!is_array($res)) {
            return yqerr($res);
        }

        return yqok($res);
    }

    public function addressFill(Request $request)
    {
        $res = SpinWheelService::getInstance()->addressFill($request);
        if ($res != 0) {
            return yqerr($res);
        }

        return yqok();
    }

    public function lotteryLog(Request $request)
    {
        $res = SpinWheelService::getInstance()->getLotteryLog($request);
        return yqok($res);
    }
}
